package thread.cas;

import java.util.concurrent.atomic.AtomicInteger;

//多线程争用的数据类
class Counter {
    //int count = 0;
    //使用AtomicInteger代替基本数据类型
    AtomicInteger count = new AtomicInteger(0);

    public int getCount() {
        //return count;
        return count.get();
    }


    public void add() {
        //count += 1;
        count.addAndGet(1);
    }

    public void dec() {
        //count -= 1;
        count.decrementAndGet();
    }
}

//争用数据做加操作的线程
class AddDataThread extends Thread {

    Counter counter;

    public AddDataThread(Counter counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        for (int i = 0; i < AtomicTest.LOOP; ++i) {
            counter.add();
        }
    }
}

//争用数据做减法操作的线程
class DecDataThread extends Thread {

    Counter counter;

    public DecDataThread(Counter counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        for (int j = 0; j < AtomicTest.LOOP; j++) {
            counter.dec();
        }
    }
}

public class AtomicTest {
    final static int LOOP = 10000;

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread addThread = new AddDataThread(counter);
        Thread decThread = new DecDataThread(counter);
        addThread.start();
        decThread.start();
        addThread.join();
        decThread.join();
        System.out.println(counter.getCount());
    }

}